package com.heima.media.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.MediaThreadLocalUtil;
import com.heima.media.dto.*;
import com.heima.media.entity.WmNews;
import com.heima.media.entity.WmNewsMaterial;
import com.heima.media.entity.WmUser;
import com.heima.media.feign.ArticleFeign;
import com.heima.media.mapper.WmNewsMapper;
import com.heima.media.service.IAuditService;
import com.heima.media.service.IWmNewsMaterialService;
import com.heima.media.service.IWmNewsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.media.service.IWmUserService;
import com.heima.media.vo.WmNewsVo;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 自媒体图文内容信息表 服务实现类
 * </p>
 *
 * @author lqw
 * @since 2022-06-21
 */
@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements IWmNewsService {
    @Autowired
    private IWmNewsMaterialService wmNewsMaterialService;
    @Autowired
    private IAuditService auditService;
    @Autowired
    private ArticleFeign articleFeign;
    @Autowired
    private IWmUserService userService;

    /**
     * 分页展示新闻
     *
     * @param dto
     * @return
     */
    @Override
    public PageResponseResult pageList(WmNewsPageDto dto) {
        //填写分页条件
        IPage<WmNews> page = new Page<>(dto.getPage(), dto.getSize());
        LambdaUpdateWrapper<WmNews> query = new LambdaUpdateWrapper<>();
        //若有状态条件,填充状态条件
        if (dto.getStatus() != null) {
            query.eq(WmNews::getStatus, dto.getStatus());
        }
        //若有关键字,填充关键字条件
        if (!StringUtils.isEmpty(dto.getKeyword())) {
            query.like(WmNews::getTitle, dto.getKeyword());
        }
        //若有频道id,填充频道条件
        if (!StringUtils.isEmpty(dto.getChannelId())) {
            query.eq(WmNews::getChannelId, dto.getChannelId());
        }
        //若有开始发布日期和结束发布日期,填充条件
        if (!StringUtils.isEmpty(dto.getBeginPubDate()) && !StringUtils.isEmpty(dto.getEndPubDate())) {
            query.between(WmNews::getPublishTime, dto.getBeginPubDate(), dto.getEndPubDate());
        }
        query.orderByDesc(WmNews::getCreatedTime);
        //分页查询
        IPage<WmNews> iPage = this.page(page, query);
        PageResponseResult result = new PageResponseResult<>(dto.getPage(), dto.getSize(), iPage.getTotal(), iPage.getRecords());
        return result;
    }

    /**
     * 发布文章
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional //开启本地事务
    public ResponseResult submit(WmNewsDto dto) {
        //本地线程拿到用户
        User user = MediaThreadLocalUtil.get();
        if (StringUtils.isEmpty(user)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //1.判断是否存在id , 存在既是修改 ,不存在既是新增
        if (dto.getId() != null) {
            //2.若是修改
            //2.1.删除已关联素材关系,修改文章
            LambdaUpdateWrapper<WmNewsMaterial> query = new LambdaUpdateWrapper<>();
            query.eq(WmNewsMaterial::getNewsId, dto.getId());
            wmNewsMaterialService.remove(query);
        }
        //3.若是新增
        //填充数据
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto, wmNews);
        wmNews.setUserId(user.getUserId());//补充userID
        wmNews.setCreatedTime(new Date());//补充创建时间
        wmNews.setSubmitedTime(new Date());//补充提交时间
        wmNews.setImages(JSON.toJSONString(dto.getImages()));//补充图片
        //提取内容中的图片
        List<ImageDto> contentImages = getContentImages(wmNews.getContent());
        if (dto.getType() == -1) {
            //随机从内容中提取图片作封面
            //判断内容图片数量
            if (contentImages.size() <= 0) {
                //修改类型为无图
                wmNews.setType(0);
            } else if (contentImages.size() < 3) {
                //修改类型为单图
                wmNews.setType(1);
                //从内容图片中去第一张作为封面
                List<ImageDto> imageDtos = contentImages.subList(0, 1);
                wmNews.setImages(JSON.toJSONString(imageDtos));
            } else {
                //修改类型为多图
                wmNews.setType(3);
                ////从内容图片中取前三张作为封面
                List<ImageDto> imageDtos = contentImages.subList(0, 3);
                wmNews.setImages(JSON.toJSONString(imageDtos));
            }
        }

        //保存文章
        //此时保存为草稿
        //this.save(wmNews);
        this.saveOrUpdate(wmNews);//根据id,若有id修改,没有则保存
        //4.若不是存入草稿
        if (dto.getStatus() != 0) {
            //4.1.关联内容中的图片与素材的关系
            saveContact(wmNews, contentImages, 0);//0是关联内容图片
            //4.2.关联封面中的图片与素材的关系
            String images = wmNews.getImages();
            List<ImageDto> imageDtos = JSON.parseArray(images, ImageDto.class);
            saveContact(wmNews, imageDtos, 1);//1是关联封面图片
            //自动审核,成功保存到作者文章库中
            // 开始自动审核文章  需要异步处理
            System.out.println(Thread.currentThread().getName() + " 开始调用自动审核服务...");
            auditService.autoAudit(wmNews);
        }
        //模拟报错
        //int num = 1/0;
        return ResponseResult.okResult();
    }

    /**
     * 媒体审核分页展示
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findPageByName(NewsAuthDto dto) {
        IPage<WmNews> page = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmNews> query = new LambdaQueryWrapper<>();
        //若前端传来title关键词添加查询条件
        if (!StringUtils.isEmpty(dto.getTitle())) {
            query.like(WmNews::getTitle, dto.getTitle());
        }
        //按发布时间倒叙
        query.orderByDesc(WmNews::getPublishTime);
        IPage<WmNews> iPage = this.page(page, query);
        List<WmNews> newsList = iPage.getRecords();
        //创建返回数据对象
        List<WmNewsVo> voList = new ArrayList<>();
        // 查询作者信息
        // todo 优化思路: 获取当前页数据所有的用户id,做一次in查询,拿到结果后对应userId设置name
        //拿到当前页所有的用户id
        /*List<Integer> userIds = new ArrayList<>();
        for (WmNews wmNews : newsList) {
            userIds.add(wmNews.getUserId());
        }*/
        for (WmNews wmNews : newsList) {
            WmNewsVo wmNewsVo = new WmNewsVo();
            BeanUtils.copyProperties(wmNews, wmNewsVo);
            WmUser wmUser = userService.getById(wmNews.getUserId());
            wmNewsVo.setAuthorName(wmUser.getName());
            voList.add(wmNewsVo);
        }
        return new PageResponseResult(dto.getPage(), dto.getSize(), iPage.getTotal(), voList);
    }

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    @Value("${topic.upDownTopic}")
    private String upDownTopic;
    /**
     * 文章上架或者下架
     *
     * @param dto
     * @return
     */
    @Override
    //@GlobalTransactional //开启全局事务
    public ResponseResult downOrUp(DownOrUpDto dto) {
        // 根据id查询文章
        WmNews wmNews = this.getById(dto.getId());
        // 判断文章是否存在
        if (wmNews == null) return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        // 判断文章是否已发布
        if (wmNews.getStatus() != 9) return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        // 更新文章的上下架状态
        wmNews.setEnable(dto.getEnable() == 1 ? true : false);
        this.updateById(wmNews);
        //封装数据
        /*ArticleIsDownDto articleIsDownDto = new ArticleIsDownDto();
        articleIsDownDto.setId(id);
        articleIsDownDto.setIs_down(dto.getEnable());
        //远程调用修改文章的上架下架状态;
        articleFeign.downOrUp(articleIsDownDto);*/
        //改用Kafka发送消息
        //自媒体中的enable和文章的正好相反,若enable=1就是上架
        kafkaTemplate.send(upDownTopic,wmNews.getArticleId().toString(),dto.getEnable()==1?"true":"false");
        return ResponseResult.okResult();
    }

    /**
     * 根据id查询自媒体文章
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult findNewsVoById(Integer id) {
        WmNews wmNews = this.getById(id);
        WmUser wmUser = userService.getById(wmNews.getUserId());
        WmNewsVo wmNewsVo = new WmNewsVo();
        BeanUtils.copyProperties(wmNews, wmNewsVo);
        wmNewsVo.setAuthorName(wmUser.getName());
        return ResponseResult.okResult(wmNewsVo);
    }

    /**
     * 人工审核
     *
     * @param dto
     * @param type  1:成功   2:失败
     * @return
     */
    @Override
    public ResponseResult auth(NewsAuthDto dto, int type) {
        //根据id查询出新闻
        WmNews wmNews = this.getById(dto.getId());
        if (type == 1) {
            //审核成功,修改状态为4 :人工审核成功
            wmNews.setStatus(4);
            this.updateById(wmNews);
            //发布文章
            auditService.autoAudit(wmNews);
        } else if (type == 2) {
            //审核失败,修改状态为2 :审核失败
            wmNews.setStatus(2);
            //记录驳回原因
            wmNews.setReason(dto.getMsg());
            this.updateById(wmNews);
        }
        return ResponseResult.okResult();
    }

    /**
     * 保存图片与素材的关系
     *
     * @param wmNews
     * @param contentImages
     */
    private void saveContact(WmNews wmNews, List<ImageDto> contentImages, Integer type) {
        Integer order = 0;
        for (ImageDto contentImage : contentImages) {
            Integer materialId = contentImage.getId();
            WmNewsMaterial wmNewsMaterial = new WmNewsMaterial();
            wmNewsMaterial.setNewsId(wmNews.getId());
            wmNewsMaterial.setMaterialId(materialId);
            wmNewsMaterial.setType(type);
            wmNewsMaterial.setOrd(order);
            wmNewsMaterialService.save(wmNewsMaterial);
            order++;
        }
    }

    /**
     * 提取内容中的图片
     *
     * @param content
     * @return
     */
    private List<ImageDto> getContentImages(String content) {
        List<ContentDto> contentDtos = JSON.parseArray(content, ContentDto.class);
        List<ImageDto> contentImages = new ArrayList<>();
        for (ContentDto contentDto : contentDtos) {
            if ("image".equals(contentDto.getType())) {
                String url = contentDto.getValue();
                Integer id = contentDto.getId();
                ImageDto imageDto = new ImageDto();
                imageDto.setUrl(url);
                imageDto.setId(id);
                contentImages.add(imageDto);
            }
        }
        return contentImages;
    }


}
